import { useTableScroll } from '@/hooks/useTableScroll';
import {
  getRechargeServiceFeeList,
  rechargeServiceFee,
} from '@/services/financial-center';
import { FormatNumber } from '@/utils/format';
import { accDiv } from '@/utils/math';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Form, Input, Modal, Radio, Typography, message } from 'antd';
import { useRef, useState } from 'react';
const { Text } = Typography;
const ServiceRecharge = () => {
  const [count] = useState(0);
  const tableScrollHeight = useTableScroll({}, count);
  const actionRef = useRef<ActionType>();
  const [showTipModal, setShowTipModal] = useState(false);
  const { initialState, refresh } = useModel('@@initialState');
  const columns: ProColumns<any>[] = [
    {
      title: '充值时间',
      dataIndex: 'createTime',
      width: 160,
    },
    {
      title: '支付编号',
      dataIndex: 'id',
      width: 160,
    },
    {
      title: '充值金额',
      dataIndex: 'payStatus',
      width: 160,
      render: (_, record) => {
        return (
          <Text
            // @ts-ignore
            type={`${record.payStatus === 'payed' ? 'success' : 'default'}`}
          >
            {record.amount / 100}
          </Text>
        );
      },
    },
    {
      title: '充值前余额',
      dataIndex: 'beforeAmount',
      width: 160,
    },
    {
      title: '充值后余额',
      dataIndex: 'afterAmount',
      width: 160,
    },
    {
      title: '付款状态',
      dataIndex: 'payStatus',
      width: 160,
      render: (_, record) => {
        const obj = {
          wait_pay: { text: '未付款', type: 'danger' },
          payed: { text: '已付款', type: 'success' },
          cancelled: { text: '充值失败' },
        } as any;
        return (
          <Text {...obj[record.payStatus]}>{obj[record.payStatus].text}</Text>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: 160,
      render: (_, record) => {
        if (record.payStatus === 'wait_pay') {
          return (
            <div
              className="text-[#00bdff] cursor-pointer"
              onClick={() => {
                if (record.lastPayUrl) {
                  window.open(record.lastPayUrl);
                  setShowTipModal(true);
                }
              }}
            >
              去付款
            </div>
          );
        }
        return null;
      },
    },
  ];
  const [loading, setLoading] = useState(false);

  const handleOnRecharge = (values: any) => {
    setLoading(true);
    rechargeServiceFee({
      payMethod: 0,
      payChannelMoney: Number(values.amount * 100).toFixed(),
      billPayMethod: 'alipay_web_page',
      amount: Number(values.amount * 100).toFixed(),
    })
      .then((res: any) => {
        if (res.success) {
          window.open(res.data);
          setShowTipModal(true);
        } else {
          message.error(res.resultMessage);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
    <div>
      <div className="bg-white mb-6 p-4 rounded-lg">
        <div className="border inline-block py-2 px-4">
          服务费账户余额：¥
          {FormatNumber(accDiv(initialState?.currentUser.moneyLeft, 100))}
        </div>
        <div className="text-[red] my-6 text-[12px]">
          禁止将支付工具用于黄、赌、毒等国家法律不允许的行业使用，如有发现将终止合作。
        </div>
        <Form
          layout="vertical"
          onFinish={handleOnRecharge}
          wrapperCol={{ span: 4 }}
        >
          <Form.Item
            name={'amount'}
            label="充值金额"
            rules={[{ required: true, message: '请输入充值金额' }]}
          >
            <Input placeholder="请输入充值金额" />
          </Form.Item>
          {/* <Form.Item label="备注" name={'remark'}>
            <Input placeholder="备注" />
          </Form.Item> */}
          <Form.Item label="充值方式" name="type" initialValue={'1'}>
            <Radio.Group>
              <Radio value="1">支付宝在线支付</Radio>
              {/* <Radio value="2">转账支付</Radio> */}
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Button loading={loading} htmlType="submit" type="primary">
              提交支付
            </Button>
          </Form.Item>
        </Form>
      </div>
      <ProTable
        scroll={{ y: tableScrollHeight, x: 200 }}
        rowKey="id"
        search={false}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        request={async (params: any) => {
          const { current, ...rest } = params;
          try {
            const { data, count, success } = (await getRechargeServiceFeeList({
              pageNo: (current - 1) as number,
              ...rest,
            })) as any;
            return {
              data: data,
              total: count,
              success,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
            };
          }
        }}
        actionRef={actionRef}
        cardBordered
        columnsState={{
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
      />
      <Modal
        open={showTipModal}
        okText="我已支付"
        title="请在新打开的页面完成支付"
        onOk={() => {
          actionRef.current?.reload();
          setShowTipModal(false);
          refresh();
        }}
        onCancel={() => {
          actionRef.current?.reload();
          setShowTipModal(false);
          refresh();
        }}
      >
        <div>
          支付完成前请不要关闭当前窗口，支付成功后，您可以在服务费充值明细中查看。
        </div>
      </Modal>
    </div>
  );
};

export default ServiceRecharge;
